import {AxiosPromise, AxiosRequestConfigs} from "@/types";
import xhr from './xhr'
import {buildURL} from "@/url";
import {transformRequest, transformResponse} from "@/utils/data";
import {processHeaders} from "@/utils/headers";

function axios(config: AxiosRequestConfigs): AxiosPromise {
    //TODO
    processConfig(config);
    return xhr(config).then(res => {
        return transformResponseData(res)
    });
}

function processConfig(config: AxiosRequestConfigs): void {
    config.url = transformURL(config);
    config.headers = transformHeaders(config);
    config.data = transformRequest(config);
}

function transformURL(config: AxiosRequestConfigs): string {
    const {url, params} = config;
    return buildURL(url!, params);
}

function transformRequestData(config: AxiosRequestConfigs): any {
    return transformRequest(config.data);
}

function transformResponsetData(config: AxiosRequestConfigs): any {
    return transformRequest(config.data);
}

function transformHeaders(config: AxiosRequestConfigs): any {
    const {headers = {}, data} = config;
    return processHeaders(headers, data);
}

function transformResponseData(res: AxiosPromise): AxiosPromise {
    res.data = transformResponse(res.data);
    return res;
}

export default axios;